package com.yby6.web.controller.tool;

import com.yby6.common.exception.CustomException;
import com.yby6.common.utils.StringUtils;
import com.yby6.common.utils.upload.OSSFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.yby6.common.core.AjaxResult;
import com.yby6.framework.fastdfs.UploadService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: yangbuyi-rbac
 * @ClassName: UploadController
 * @create: 2021-05-14 23:28
 * @author: Yang Shuai
 * @since： JDK1.8
 * @UploadController: 通用文件上传|下载$
 **/

@RestController
@RequestMapping("upload")
public class UploadController {

	/**
	 * 上传服务
	 */
	@Autowired
	private UploadService uploadService;

	/**
	 * 响应
	 */
	@Autowired
	private HttpServletResponse response;

	/**
	 * 阿里云OSS下载文件
	 *
	 * @param name 下载后的名字
	 * @param url  url
	 */
	@PostMapping("downloadFile")
	public void downloadFile(String name, String url) {
		try {
			if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(url)) {
				OSSFileUtil.downloadFile(name, url, response);
			} else {
				throw new CustomException("参数不允许为空");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 阿里云上传文件oss的结果
	 *
	 * @param mf       文件数据
	 * @param fileName 文件名称
	 * @return {@link AjaxResult}
	 */
	@PostMapping("uploadFileOssResult")
	public AjaxResult uploadFileOssResult(MultipartFile mf, String fileType) throws IOException {
		if (null != mf) {
			return AjaxResult.success(OSSFileUtil.uploadFile(mf, fileType));
		} else {
			return AjaxResult.error("上传文件失败");
		}
	}

	/**
	 * 七牛云文件上传
	 * @param file
	 * @return
	 */
	@PostMapping("/qiniuOssUploadFile")
	public AjaxResult qiniuOssUploadFile(MultipartFile mf) {
		return AjaxResult.success(uploadService.qiniuOssUploadFile(mf));
	}

	/**
	 * fast dfs文件上传
	 *
	 * @param mf
	 * @return AjaxResult
	 */
	@PostMapping("doUploadImage")
	public AjaxResult uploadFile(MultipartFile mf, String fileName) {
		if (null != mf) {
			return AjaxResult.success(this.uploadService.uploadImage(mf, fileName));
		} else {
			return AjaxResult.error("上传文件失败");
		}
	}

	/**
	 * fast dfs 删除远程服务器文件
	 *
	 * @param path
	 */
	@PostMapping("deleteUploadImage")
	public AjaxResult deleteUploadImage(String path) {
		this.uploadService.deleteFile(path);
		return AjaxResult.success("文件删除成功");
	}

}
